<?php

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/10/24
 * Time: 10:49
 */

namespace app\api\model;


use redis\RedisPackage;
use think\Db;
use app\api\model\WorkTime;
use think\Exception;
use think\Model;


class QuotationListOperation extends Model
{
    /*
     *
     * 施工节点
     */
    public function ProcessTemplateList($orderId)
    {
        $envelopes = db('envelopes')->field('envelopes.envelopes_id,order.pro_id')->join('order', 'order.order_id=envelopes.ordesr_id', 'left')->where('type', 1)->where('ordesr_id', $orderId)->find();

        $envelopes_product      = db('envelopes_product')->where('envelopes_id', $envelopes['envelopes_id'])->select();
        $capital                = db('capital')->where('types', 1)->where('enable', 1)->where('envelopes_id', $envelopes['envelopes_id'])->column('projectId');
        $work_template_detailed = Db::connect('database.zong')->table('work_template_detailed')->whereIn('detailed_id', $capital)->column('work_template_id');
        $work_template_products = Db::connect('database.zong')->table('work_template_products')->whereIn('products_id', array_column($envelopes_product, 'products_id'))->column('work_template_id');
        $work_template_category = Db::connect('database.zong')->table('work_template_category')->where('goods_category_id', $envelopes['pro_id'])->column('work_template_id');
        $list                   = array_merge($work_template_products, $work_template_category, $work_template_detailed);
        return ['list' => $list, 'capitalId' => $capital];
    }

    /*
     *
     * 施工进度
     */
    public function ConstructionProgressModel($capital, $workProcess, $orderId, $afferentId)
    {
        $work_capital_type = \db('work_capital_type')->where('order_id', $orderId)->where('agent', 0)->select();
        $orderState        = \db('order')->where('order_id', $orderId)->value('state');
        $toSaveTheType     = [];
        $Additions         = 0;
        if (!empty($work_capital_type)) {
            $afferentId    = $work_capital_type[0]['work_template_id'];
            $toSaveTheType = self::toSaveTheTypeOfWork($work_capital_type);
            if (!empty($toSaveTheType)) {
                $list          = $capital->workingProcedure($orderId, 1, $toSaveTheType[0]['capital_id']);
            } else {
                $list = $capital->workingProcedure($orderId);
                $Additions = 1;
            }
        } else {
            $list = $capital->workingProcedure($orderId);
            $Additions = 1;
        }
        if (!empty($list)) {
            $workProcessId = array_merge(array_unique(array_column($list, 'workProcessId')));
            $workProcessIdString = null;
            foreach ($workProcessId as $item) {
                if (!empty($item)) {
                    $workProcessIdString .= $item . ',';
                }
            }
        }
        $WorkTemplateDetailed = null;
        if (!empty($workProcessIdString)) {
            $WorkTemplateDetailed = $workProcess->WorkTemplateDetailed($workProcessIdString)->toArray();
        }

        if (!empty($list)) {
            foreach ($list as $l => $item) {
                $list[$l]['work_capital_procedure_id'] = 0;
                $list[$l]['workCapitalRelationSaveId'] = 0;
            }
        }
        $work_process_template = [];
        if ($afferentId != 0 && !empty($list)) {
            $work_process_template = $workProcess->WorkTemplate($afferentId)->toArray();
            $excludeList           = [];
            if (!empty($WorkTemplateDetailed)) {
                $id                       = array_column($work_process_template, 'id');
                $ids                      = array_column($WorkTemplateDetailed, 'id');
                $o                        = array_diff($ids, $id);
                $WorkTemplateDetailedLsit = [];
                foreach ($WorkTemplateDetailed as $k => $value) {
                    foreach ($o as $item) {
                        if ($value['id'] == $item) {
                            $WorkTemplateDetailedLsit[$k]['title']         = $value['title'];
                            $WorkTemplateDetailedLsit[$k]['workTypeTitle'] = $value['workTypeTitle'];
                            $WorkTemplateDetailedLsit[$k]['important'] = $value['important'];
                            $WorkTemplateDetailedLsit[$k]['workTypeId']    = $value['workTypeId'];
                            $WorkTemplateDetailedLsit[$k]['id']            = $value['id'];
                            $WorkTemplateDetailedLsit[$k]['workSort']      = $value['workSort'];
                            $WorkTemplateDetailedLsit[$k]['workTypeSort']  = $value['workTypeSort'];
                            $WorkTemplateDetailedLsit[$k]['start_day']     = '';
                            $WorkTemplateDetailedLsit[$k]['end_day']       = '';
                        }
                    }
                }
                $work_process_template = array_merge($work_process_template, $WorkTemplateDetailedLsit);
            }
        } else {
            if (!empty($WorkTemplateDetailed)) {
                $WorkTemplateDetailedLsit = [];
                foreach ($WorkTemplateDetailed as $k => $value) {
                    $WorkTemplateDetailedLsit[$k]['title']         = $value['title'];
                    $WorkTemplateDetailedLsit[$k]['workTypeTitle'] = $value['workTypeTitle'];
                    $WorkTemplateDetailedLsit[$k]['important'] = $value['important'];
                    $WorkTemplateDetailedLsit[$k]['workTypeId']    = $value['workTypeId'];
                    $WorkTemplateDetailedLsit[$k]['id']            = $value['id'];
                    $WorkTemplateDetailedLsit[$k]['workSort']      = $value['workSort'];
                    $WorkTemplateDetailedLsit[$k]['workTypeSort']  = $value['workTypeSort'];
                    $WorkTemplateDetailedLsit[$k]['start_day']     = '';
                    $WorkTemplateDetailedLsit[$k]['end_day']       = '';
                }
                $work_process_template = $WorkTemplateDetailedLsit;
            }
        }

        $op = [];
        foreach ($work_process_template as $k => $value) {
            foreach ($list as $item) {
                if (in_array($value['id'], explode(",", $item['workProcessId'])) && !empty($item['workProcessId'])) {
                    $work_process_template[$k]['list'][] = $item;
                }
            }
        }
        $merge = $work_process_template;
        if (!empty($toSaveTheType)) {
            foreach ($toSaveTheType as $k1 => $item) {
                foreach ($merge as $k => $list) {
                    if ($item['workTypeId'] == $list['workTypeId'] && $item['id'] == $list['id']) {
                        if (isset($list['list'])) {
                            $toSaveTheType[$k1]['list'] = array_merge($item['list'], $list['list']);
                        }
                        unset($merge[$k]);
                    }
                }
            }
            $merge = array_merge($merge, $toSaveTheType);
        }
        $merge  = $workProcess::arraySort($merge, 'workTypeSort', SORT_ASC);
        $temp   = array();
        $result = array();
        $action = 0;
        foreach ($merge as $k => $item) {
            if ($item['workTypeTitle']  == "完工验收") {
                break;
            }
            if (isset($item['list'])) {
                $working_start = "";
                $working_end   = "";
                if (!in_array($item['workTypeTitle'], $temp)) {
                    array_push($temp, $item['workTypeTitle']);
                    $result[count($temp) - 1]['typeWork']       = $item['workTypeTitle'];
                    $result[count($temp) - 1]['typeWorkId']     = $item['workTypeId'];
                    $result[count($temp) - 1]['workTypeSort']   = $item['workTypeSort'];
                    $result[count($temp) - 1]['workTemplateId'] = empty($afferentId) ? null : $afferentId;
                    if ($item['workTypeTitle'] == "完工验收") {
                        $action = 1;
                    }
                }

                if (!empty($item['list'][0]['sta_time']) && isset($item['start_day']) && $item['start_day'] != 0) {

                    $sta_time = date('Y-m-d', ($item['list'][0]['sta_time'] + ($item['start_day'] - 1) * 86400));
                    $end_day  = date('Y-m-d', ($item['list'][0]['sta_time'] + ($item['end_day'] - 1) * 86400));

                    $work           = new WorkTime();
                    $working_hours  = $work->get_working_hours(strtotime($sta_time), strtotime($end_day));
                    $working_start  = $sta_time;
                    $working_end    = $end_day;
                    $start_day_more = ($item['end_day'] - 1) - ($item['start_day'] - 1);
                    if ($working_hours < $start_day_more) {
                        $working_end = date('Y-m-d', strtotime('2023-01-03') + (($start_day_more - $working_hours) * 86400));
                    }
                }
                if (isset($item['working_start']) && isset($item['working_end'])) {
                    $working_start = $item['working_start'];
                    $working_end   = $item['working_end'];
                }
                $state = 0;
                if (!empty($item['list'])) {

                    $work_time = array_sum(array_column($item['list'], 'work_time'));
                    if ($work_time != 0) {
                        $state = 1;
                    }
                    //                    //0没有上传 1 可验收 2 已验收 3没有节点
                    $isNodesState = [];
                    foreach ($item['list'] as $k1 => $v) {
                        if ($v['isNodes'] == 1) {
                            $item['list'][$k1]['completionStatus'] = 1;
                        }
                        if ($v['isNodes'] == 1 && $v['leng'] == 1) {
                            $item['list'][$k1]['completionStatus'] = 1;
                        } elseif ($v['isNodes'] == 2 && ($v['leng'] != $v['adnIdLeng'])) {
                            $item['list'][$k1]['completionStatus'] = 1;
                        } elseif ($v['isNodes'] == 0 || $v['isNodes'] == 3) {
                            $item['list'][$k1]['completionStatus'] = 0;
                        } elseif ($v['isNodes'] == 2 && ($v['leng'] == $v['adnIdLeng'])) {
                            $item['list'][$k1]['completionStatus'] = 2;
                        }
                        if ($v['isNodes'] == 2 && ($v['leng'] != $v['adnIdLeng'])) {
                            $item['list'][$k1]['isNodes'] = 1;
                        }
                        if ($orderState == 7) {
                            $item['list'][$k1]['isNodes'] = 2;
                        }
                    }
                    $isNodes = array_unique(array_column($item['list'], 'completionStatus'));
                    if (in_array(1, $isNodes)) {
                        $state = 1;
                    }
                    if (in_array(2, $isNodes) && in_array(0, $isNodes)) {
                        $state = 1;
                    }
                    if (!in_array(1, $isNodes) && !in_array(0, $isNodes)) {
                        $state = 2;
                    }
                }
                if ($orderState == 7) {
                    $state = 2;
                }

                $result[count($temp) - 1]['list'][] = [
                    'workingProcedure' => $item['title'],
                    'mainNBode' => $item['important'],
                    'workingProcedureId' => $item['id'],
                    'sort' => $item['workSort'],
                    'completionStatus' => $state,
                    'data' => empty($item['list']) ? [] : $item['list'],
                    'working_start' => $working_start,
                    'working_end' => $working_end,
                    'workTypeSaveId' => isset($item['workTypeSaveId']) ? $item['workTypeSaveId'] : 0,
                ];
            }
        }
        $wan                   = [];
        // $acceptanceData        = [];
        // $list_process=$this->listProcess($orderId,3);
        // $work_capital_relation = db('work_capital_relation')
        //     ->field('work_capital_relation.id,work_capital_relation.capital_id')
        //     ->join('work_capital_procedure', 'work_capital_procedure.id=work_capital_relation.work_capital_procedure_id', 'left')
        //     ->join('work_capital_type', 'work_capital_type.id=work_capital_procedure.work_capital_type_id', 'left')
        //     ->where('order_id', $orderId)->where('type_work_id', 7)->select();
        // $status=[];
        // foreach ($list_process as $k => $item) {
        //     $workCapitalRelationSaveId = 0;
        //     foreach ($work_capital_relation as $value) {
        //         if ($item['id'] == $value['capital_id']) {
        //             $workCapitalRelationSaveId = $value['id'];
        //         }
        //     }
        //     $acceptanceData[$k]["class_b"]                   = $item['title'];
        //     $acceptanceData[$k]["completeTime"]              = "";
        //     $acceptanceData[$k]["capital_id"]                = $item['id'];
        //     $acceptanceData[$k]["orderId"]                   = $orderId;
        //     $acceptanceData[$k]["type"]                      = 2;
        //     $acceptanceData[$k]["workCapitalRelationSaveId"] = $workCapitalRelationSaveId;
        //     $isNode=0;
        //     if($item['status']==1 || $item['status']==2){
        //         $isNode=2;
        //     }
        //     $acceptanceData[$k]["isNodes"]          = $isNode;
        //     $status[]=$acceptanceData[$k]["isNodes"];
        // }
        // $status=array_unique($status);

        // if ($action == 0) {
        //     $state = 0;
        //     if (in_array(1, $status) || in_array(3, $status)|| in_array(2, $status)) {
        //         $state = 1;
        //     }
        //     if ((in_array(1, $status)|| in_array(2, $status ))&& !in_array(0, $status) && !in_array(3, $status)) {
        //         $state = 2;
        //     }
        //     // $wan = [
        //     //     0 => [
        //     //         'typeWork' => "完工验收",
        //     //         'typeWorkId' => 7,
        //     //         'workTypeSort' => 10,
        //     //         'workTemplateId' => 0,
        //     //         'list' => [[
        //     //             "workingProcedure" => "完工交付验收",
        //     //             "workingProcedureId" => 1,
        //     //             "sort" => 1,
        //     //             'typeWorkId' => 7,
        //     //             "completionStatus" => $state,
        //     //             "data" => $acceptanceData,
        //     //             "working_start" => "",
        //     //             "working_end" => "",
        //     //             "workTypeSaveId" => 0
        //     //         ]],

        //     //     ]];
        // } else {
        //     foreach ($result as $k => $item) {
        //         if ($item['typeWork'] == "完工验收") {
        //             foreach ($item['list'] as $b => $v) {
        //                 $state = 0;
        //                 if (in_array(1, $status) || in_array(3, $status)|| in_array(2, $status)) {
        //                     $state = 1;
        //                 }
        //                 if ((in_array(1, $status)|| in_array(2, $status ))&& !in_array(0, $status) && !in_array(3, $status)) {
        //                     $state = 2;
        //                 }
        //                 $result[$k]['list'][$b]['data'] = $acceptanceData;
        //                 $result[$k]['list'][$b]['completionStatus'] = $state;
        //                 $result[$k]['list'][$b]['typeWorkId'] = 7;
        //             }

        //         }
        //     }
        // }


        // $result = array_merge($result, $wan);
        foreach ($result as $k => $item) {
            $result[$k]['list'] = $workProcess::arraySort($item['list'], 'sort', SORT_ASC);
        }
        $matching = [];
        if ($afferentId != 0 && !empty($op)) {
            foreach ($op as $item) {
                $matching              = [
                    'capital_id' => $item['capital_id'],
                    'order_id' => $orderId,
                    'creation_time' => time(),
                    'work_template_id' => $afferentId,
                ];
                $work_capital_matching = \db('work_capital_matching')->where(['capital_id' => $item['capital_id'], 'order_id' => $orderId, 'work_template_id' => $afferentId])->count();
                if ($work_capital_matching == 0) {
                    \db('work_capital_matching')->insert($matching);
                }
            }
        }

        return ['Additions' => $Additions, 'result' => $result];
    }

    /*
     * 根据工种获取工序
     */
    public function getOperationModel($capital, $workProcess, $id, $capitalList)
    {
        $result             = [];
        $capitalListOrderId = \db('capital')->whereIn('capital_id', $capitalList)->select();
        if ($capitalListOrderId) {
            $list          = $capital->workingProcedure($capitalListOrderId[0]['ordesr_id'], 0, $capitalList, 0);
            $result        = $workProcess->WorkTypeAcquisitionProcess($id);
            $listExistence = [];
            foreach ($result as $k => $value) {
                $working_start                           = "";
                $working_end                             = "";
                $listExistence[$k]['workingProcedure']   = $value['title'];
                $listExistence[$k]['workingProcedureId'] = $value['id'];
                $listExistence[$k]['sort']               = $value['sort'];
                $listExistence[$k]['completionStatus']   = 0;
                $listExistence[$k]['working_start']      = 0;
                $listExistence[$k]['working_end']        = 0;
                $listExistence[$k]['workTypeSaveId']     = 0;
                $listExistence[$k]['end_day']            = $value['end_day'];
                $listExistence[$k]['start_day']          = $value['start_day'];
                foreach ($list as $l => $item) {
                    $list[$l]['isNodes'] = empty($item['isNodes']) ? 0 : 1;
                    if (in_array($value['id'], explode(",", $item['workProcessId']))) {
                        $listExistence[$k]['data'][] = $item;
                    }
                }
            }
            foreach ($listExistence as $k => $item) {
                if (!empty($item['list'][0]['sta_time']) && isset($item['start_day']) && $item['start_day'] != 0) {

                    $sta_time      = date('Y-m-d', ($item['list'][0]['sta_time'] + ($item['start_day'] - 1) * 86400));
                    $end_day       = date('Y-m-d', ($item['list'][0]['sta_time'] + ($item['end_day'] - 1) * 86400));
                    $working_start = $sta_time;
                    $working_end   = $end_day;
                }
                $state = 0;
                if (!empty($item['list'])) {
                    $completeTime = array_column($item['data'], 'completeTime');
                    $work_time    = array_sum(array_column($item['list'], 'work_time'));

                    if ($work_time != 0) {
                        $state = 1;
                    }
                    if (!in_array(0, $completeTime)) {
                        $state = 1;
                    }
                    if (0 <= strtotime(max(array_column($item['data'], 'completeTime'))) && strtotime(max(array_column($item['data'], 'completeTime')))) {
                        $state = 2;
                    }
                }
                $listExistence[$k]['completionStatus'] = $state;
                $listExistence[$k]['working_start']    = $working_start;
                $listExistence[$k]['working_end']      = $working_end;
                unset($listExistence[$k]['start_day'], $listExistence[$k]['end_day']);
                if (!isset($item['data'])) {
                    unset($listExistence[$k]);
                }
            }
            $listExistence = array_merge($listExistence);
            $result        = $workProcess::arraySort($listExistence, 'sort', SORT_ASC);
        }
        return $result;
    }

    /*
     * 主材进度
     */
    public function mainMaterialProgressModel($orderId)
    {
        $work_capital_type      = \db('work_capital_type')->where('order_id', $orderId)->where('agent', 1)->select();
        $work_capital_procedure = \db('work_capital_procedure')->whereIn('work_capital_type_id', array_column($work_capital_type, 'id'))->select();
        $work_capital_relation  = \db('work_capital_relation')
            ->field('capital.class_b,capital.capital_id,capital.ordesr_id as orderId,work_capital_relation.work_capital_procedure_id,work_capital_relation.type')
            ->Join('capital', 'work_capital_relation.capital_id=capital.capital_id', 'left')
            ->where(['capital.types' => 1, 'capital.enable' => 1, 'agency' => 0, 'work_capital_relation.type' => 1])
            ->whereIn('work_capital_relation.work_capital_procedure_id', array_column($work_capital_procedure, 'id'))
            ->group('work_capital_relation.id')
            ->select();
        $aggregate              = [];
        foreach ($work_capital_procedure as $l => $item) {
            foreach ($work_capital_type as $list) {
                $data = [];
                if ($list['id'] == $item['work_capital_type_id']) {
                    $aggregate[$l]['workTypeTitle'] = $list['type_work'];
                    $aggregate[$l]['workTypeSort']  = $list['type_sort'];
                    $aggregate[$l]['workTypeId']    = $list['type_work_id'];
                    $aggregate[$l]['id']            = $item['work_capital_type_id'];
                    $aggregate[$l]['workSort']      = $item['working_sort'];
                    $aggregate[$l]['title']         = $item['working_procedure'];
                    $aggregate[$l]['images']        = $item['images'];
                    $aggregate[$l]['type']          = $item['type'];
                    $aggregate[$l]['working_start'] = !empty($item['working_start']) ? date('Y-m-d', $item['working_start']) : '';
                    $aggregate[$l]['working_end']   = !empty($item['working_end']) ? date('Y-m-d', $item['working_end']) : '';
                    foreach ($work_capital_relation as $value) {
                        if ($item['id'] == $value['work_capital_procedure_id']) {
                            $data[] = $value;
                        }
                    }
                    $aggregate[$l]['data'] = $data;
                }
            }
        }
        $temp   = array();
        $result = array();
        foreach ($aggregate as $k => $item) {
            if (isset($item['working_start']) && isset($item['working_end'])) {
                $working_start = $item['working_start'];
                $working_end   = $item['working_end'];
            }
            if (!in_array($item['workTypeTitle'], $temp)) {
                array_push($temp, $item['workTypeTitle']);
                $result[count($temp) - 1]['typeWork']     = $item['workTypeTitle'];
                $result[count($temp) - 1]['typeWorkId']   = $item['workTypeId'];
                $result[count($temp) - 1]['workTypeSort'] = $item['workTypeSort'];
            }
            $result[count($temp) - 1]['list'][] = [
                'workingProcedure' => $item['title'],
                'workingProcedureId' => $item['id'],
                'sort' => $item['workSort'],
                'completionStatus' => empty($item['images']) ? 0 : 2,
                'data' => empty($item['data']) ? [] : $item['data'],
                'working_start' => $working_start,
                'images' => empty($item['images']) ? null : explode(',', $item['images']),
                'isMainMaterials' => 1,
                'working_end' => $working_end,
                'workTypeSaveId' => isset($item['workTypeSaveId']) ? $item['workTypeSaveId'] : 0,
            ];
        }
        return $result;
    }

    /*
     * 以保存工种
     */
    private function toSaveTheTypeOfWork($work_capital_type)
    {
        if (!empty($work_capital_type)) {
            $work_capital_procedure   = \db('work_capital_procedure')->whereIn('work_capital_type_id', array_column($work_capital_type, 'id'))->where('deleted_at', 0)->select();
            $work_capital_procedureId = \db('work_capital_relation')->join('work_capital_procedure', 'work_capital_procedure.id=work_capital_relation.work_capital_procedure_id', 'left')->whereIn('work_capital_procedure.work_capital_type_id', array_column($work_capital_type, 'id'))->column('capital_id');

            $work_capital_relation = \db('work_capital_relation')
                ->field('capital.class_b,if(ifNUll(auxiliary_project_list.completion_time,0)=0,"",FROM_UNIXTIME(auxiliary_project_list.completion_time,"%Y-%m-%d %H:%i:%s")) as completeTime,capital.capital_id,capital.ordesr_id as orderId,GROUP_CONCAT(DISTINCT app_user.username) as username,
                
          (CASE
            WHEN (auxiliary_delivery_node.state =0) or (auxiliary_delivery_node.state =2)  THEN 1
             WHEN auxiliary_delivery_node.state is  null THEN  0
             WHEN auxiliary_delivery_node.state =1 THEN  2
             WHEN GROUP_CONCAT(DISTINCT auxiliary_delivery_schedule.id) is null THEN 3
             WHEN GROUP_CONCAT(DISTINCT app_user.username) is null THEN 4
             
                 ELSE 0 END
              ) as isNodes,
               GROUP_CONCAT(DISTINCT auxiliary_delivery_schedule.id) as auxiliary_delivery_scheduleId,
               LENGTH(GROUP_CONCAT(DISTINCT auxiliary_delivery_schedule.id))- LENGTH(REPLACE(GROUP_CONCAT(DISTINCT auxiliary_delivery_schedule.id), ",", ""))+1 as leng,
                LENGTH(GROUP_CONCAT(DISTINCT if(auxiliary_delivery_node.state=1 , auxiliary_delivery_node.auxiliary_delivery_schedul_id,null)))- LENGTH(REPLACE(GROUP_CONCAT(DISTINCT if(auxiliary_delivery_node.state=1 ,auxiliary_delivery_node.auxiliary_delivery_schedul_id,null)), ",", ""))+1 as adnIdLeng,
                GROUP_CONCAT(DISTINCT if(auxiliary_delivery_node.state=1, auxiliary_delivery_node.auxiliary_delivery_schedul_id,null)) as ss,
              
                work_capital_relation.work_capital_procedure_id,
                work_capital_relation.id as workCapitalRelationSaveId,
                GROUP_CONCAT(DISTINCT detailed_work_process.work_process_id) as workProcessId,
                sum(app_user_order_capital.work_time) as work_time')
                ->Join('capital', 'work_capital_relation.capital_id=capital.capital_id', 'left')
                ->Join('detailed_work_process', 'detailed_work_process.detailed_id=capital.projectId', 'left')
                ->Join('auxiliary_project_list', 'auxiliary_project_list.capital_id=capital.capital_id and auxiliary_project_list.delete_time is null', 'left')
                ->Join('auxiliary_delivery_schedule', 'auxiliary_project_list.id=auxiliary_delivery_schedule.auxiliary_project_list_id and auxiliary_delivery_schedule.delete_time is null', 'left')
                ->Join('auxiliary_delivery_node', 'auxiliary_delivery_node.auxiliary_delivery_schedul_id=auxiliary_delivery_schedule.id', 'left')
                ->Join('app_user_order_capital', 'app_user_order_capital.capital_id=capital.capital_id and app_user_order_capital.deleted_at is null and `app_user_order_capital`.`order_id` = capital.ordesr_id ', 'left')
                ->Join('app_user', 'app_user_order_capital.user_id=app_user.id', 'left')
                ->where(['capital.types' => 1, 'capital.enable' => 1, 'agency' => 0])
                ->whereNull('capital.up_products_time')
                ->whereIn('work_capital_relation.work_capital_procedure_id', array_column($work_capital_procedure, 'id'))
                ->group('work_capital_relation.id')
                ->select();
            $aggregate             = [];
            foreach ($work_capital_procedure as $l => $item) {
                foreach ($work_capital_type as $list) {
                    $data = [];
                    if ($list['id'] == $item['work_capital_type_id']) {
                        $aggregate[$l]['workTypeTitle']  = $list['type_work'];
                        $aggregate[$l]['workTypeSort']   = $list['type_sort'];
                        $aggregate[$l]['workTypeId']     = $list['type_work_id'];
                        $aggregate[$l]['typeSaveId']     = $list['id'];
                        $aggregate[$l]['list']           = [];
                        $aggregate[$l]['id']             = $item['working_procedure_id'];
                        $aggregate[$l]['workTypeSaveId'] = $item['id'];
                        $aggregate[$l]['important'] = Db::connect('database.zong')->table('work_process')->whereIn('id', $item['working_procedure_id'])->where('status', 1)->value('important');
                        $aggregate[$l]['workSort']       = $item['working_sort'];
                        $aggregate[$l]['title']          = $item['working_procedure'];
                        $aggregate[$l]['working_start']  = !empty($item['working_start']) ? date('Y-m-d', $item['working_start']) : '';
                        $aggregate[$l]['working_end']    = !empty($item['working_end']) ? date('Y-m-d', $item['working_end']) : '';
                        $aggregate[$l]['capital_id']     = array_merge(array_unique($work_capital_procedureId));
                        foreach ($work_capital_relation as $value) {
                            //0没有上传 1 可验收 2 已验收 3没有节点
                            if ($item['id'] == $value['work_capital_procedure_id']) {
                                $data[] = $value;
                            }
                        }
                        $aggregate[$l]['list'] = $data;
                    }
                }
            }
        }

        return $aggregate;
    }
    /*
     * 必要检查数据
     */
    public function listProcess($orderId, $type)
    {
        $list_process          = Db::connect(config('database.zong'))->table('sys_config')->where('statusss', 1)->where('keyss', 'list_process')->find();
        $list_process          = json_decode($list_process['valuess'], true);
        $work_check = db('work_check')->where('order_id', $orderId)->whereIn('work_title_id', [1, 2, 3, 4])->where('delete_time', 0)->order('id desc')->field("state,img,no_watermark_image")->select();
        $detailed_final_acceptance = Db::connect(config('database.zong'))->table('order_acceptance_content')->where('order_id', $orderId)->where('delete_time', 0)->select();
        $isState = 0;
        if ((empty($work_check) && empty($detailed_final_acceptance)) ||  !empty($detailed_final_acceptance)) {
            $isState = 1;
        }
        if ($type == 1) {
            return $isState;
        }
        foreach ($list_process as $k => $item) {
            $state = db('work_check')->where('work_title_id', $item['id'])->where('order_id', $orderId)->where('delete_time', 0)->order('id desc')->field("state,img,no_watermark_image")->find();
            $list_process[$k]["status"]                   = empty($state) ? 0 : $state['state'];
            $list_process[$k]["picture"]                   = empty($state) ? null : json_decode($state['img'], true);
            $list_process[$k]["no_watermark_image"]                   = empty($state) ? null : json_decode($state['no_watermark_image'], true);
        }
        if ($isState == 1) {
            $list_process = [];
            $capitalList = [];
            $detailed_final_acceptance = Db::connect(config('database.zong'))->table('detailed_final_acceptance')->where('delete_time', 0)->select();
            $capital = db('capital')->where('ordesr_id', $orderId)->where('types', 1)->where('enable', 1)->select();

            foreach ($detailed_final_acceptance as $item) {
                $acceptance_standard = json_decode($item['acceptance_standard'], true);
                if (!empty($acceptance_standard)) {
                    foreach ($acceptance_standard as $k => $j) {
                        $acceptance_standard[$k]['stste'] = 1;
                    }
                }

                if ($item['type'] == 1) {
                    $list_process[] = ['title' => $item['acceptance_project'], 'type' => 1, 'id' => $item['id'], 'list' => $acceptance_standard];
                }
                if ($item['type'] == 2) {
                    foreach ($capital as $value) {
                        if ($value['projectId'] == $item['detailed_id']) {
                            $capitalList[] = ['title' => $item['acceptance_project'], 'type' => 2, 'id' => $item['id'], 'projectId' => $value['projectId'], 'list' => $acceptance_standard];
                        }
                    }
                }
            }
            $list_processList[] = ['title' => '常规验收(所有订单都需要验收，没有可直接通过)', 'date' => $list_process];
            $uniqueData = [];

            // 遍历原始数据
            foreach ($capitalList as $item) {
                // 如果 uniqueData 中还没有这个 projectId，则添加
                if (!isset($uniqueData[$item['projectId']])) {
                    $uniqueData[$item['projectId']] = $item;
                }
            }

            // 重新索引结果数组
            $uniqueData = array_values($uniqueData);
            $uniqueList = [];
            if (!empty($uniqueData)) {
                $uniqueList[] = ['title' => '主控验收(与报价关联的主要控制节点)', 'date' => $uniqueData];
            }
            $workCheck = db('work_check')->where('order_id', $orderId)->where('work_title_id', 5)->where('delete_time', 0)->order('id desc')->field("state,img,no_watermark_image,id")->find();
            $listProcess['list'] = array_merge($list_processList, $uniqueList);
            $listProcess['describe'] = '完工自验收提示说明：
1、请在完工时统一上传，暂不支持分批次上传和验收
2、有不通过的项目无法转发用户验收，需要内部整改后转发
3、主控项目，根据报价清单中的清单匹配展示，如果节点已验收通过，系统会默认通过，但仍然需要店长验收时把关。
4、完工照片，1W以下工地可使用手机相册上传，1W以上工地需要使用水印相机拍摄上传
5、KA订单，需要额外上传完工验收单';
            $listProcess['picture'] = empty($workCheck) ? null : json_decode($workCheck['img'], true);
            $listProcess["picture"]                   = empty($listProcess['picture']) ? json_decode($workCheck['no_watermark_image'], true) : $listProcess['picture'];
            $order_completion = Db::connect(config('database.zong'))->table('order_completion')->where('order_id', $orderId)->where('work_check_id', $workCheck['id'])->order('id desc')->find();
            
            $listProcess["inspectionPassTime"] = empty($order_completion) ? '' : date('Y-m-d H:i:s', $order_completion['inspection_pass_time']); //验收时间
            $listProcess["inspectionState"] = empty($order_completion) ? null : "验收通过"; //验收结果
            $listProcess["inspectionType"] = 0; //验收结果
            if (empty($order_completion) && !empty($workCheck)) {
                $listProcess["inspectionType"] = 3;
            }
            $listProcess["issueImages"] = null;
            $listProcess["inspectionFailureContent"] = '';
            $listProcess["inspectionFailureReason"] = NULL;
            $listProcess["remarks"] = empty($order_completion) ? '' : $order_completion['remarks'];

            if (!empty($order_completion)) {
                if ($order_completion['inspection_type'] == 2) {
                    $listProcess["inspectionState"] = "验收不通过-需要整改";
                    $listProcess["inspectionType"] = 2;
                    $listProcess["inspectionFailureReason"] = explode(",", $order_completion['inspection_failure_reason']);
                    $listProcess["inspectionFailureContent"] = $order_completion['inspection_failure_content'];
                    $listProcess["issueImages"] = json_decode($order_completion['issue_images'], true);
                }
                if ($order_completion['inspection_type'] == 3) {
                    $listProcess["inspectionType"] = 1;
                }
                if ($order_completion['inspection_type'] == 1 || $order_completion['inspection_type'] == 0) {
                    $listProcess["inspectionType"] = 3;
                }
            }

            $list_process = $listProcess;
        }

        return $list_process;
    }
    /*
     *
     * 施工进度
     */
    public function newConstructionProgressModel($orderId, $workProcess)
    {
        $auxiliaryProjectList = db('auxiliary_delivery_schedule')
            ->where('auxiliary_project_list.order_id', $orderId)
            ->field('
                auxiliary_delivery_schedule.work_process_accept_std_upload_ckp,
                auxiliary_project_list.work_process_title,
                auxiliary_project_list.work_process_important,
                auxiliary_project_list.work_process_sort,
                auxiliary_delivery_schedule.work_process_accept_std_upload_req,
                capital.capital_id,
                concat(capital.class_b,"(",square,"/",company,")") as class_b,
                order.state,
                auxiliary_project_list.working_start,
                auxiliary_project_list.working_end,
                auxiliary_delivery_node.type,
                auxiliary_delivery_schedule.work_process_accept_std_is_focus,
                auxiliary_delivery_schedule.id as ids,
                auxiliary_delivery_schedule.completion_time,
                group_concat(auxiliary_delivery_node.node_id) as node_ids,
                group_concat(auxiliary_delivery_node.adn_id) as adn_id,
                auxiliary_project_list.work_process_id,
                auxiliary_project_list.work_type_sort,
                auxiliary_project_list.work_type_id,
                auxiliary_project_list.work_type_title,
                auxiliary_project_list.id,
                GROUP_CONCAT(DISTINCT app_user.username) as username,
                auxiliary_project_list.work_process_sort
            ')
            ->join('auxiliary_project_list', 'auxiliary_project_list.id=auxiliary_delivery_schedule.auxiliary_project_list_id', 'left')
            ->join('capital', 'capital.capital_id=auxiliary_project_list.capital_id', 'left')
            ->Join('app_user_order_capital', 'app_user_order_capital.capital_id=capital.capital_id and app_user_order_capital.deleted_at is null and `app_user_order_capital`.`order_id` = capital.ordesr_id ', 'left')
            ->Join('app_user', 'app_user_order_capital.user_id=app_user.id', 'left')
            ->join('auxiliary_delivery_node', 'auxiliary_delivery_node.auxiliary_delivery_schedul_id=auxiliary_delivery_schedule.id', 'left')

            ->join('order', 'order.order_id=auxiliary_project_list.order_id', 'left')
            ->where('auxiliary_delivery_schedule.work_process_accept_std_type', 3)
            ->where('auxiliary_project_list.work_process_type', 1)
            ->group('auxiliary_delivery_schedule.id');

        $list = $auxiliaryProjectList->where('auxiliary_project_list.work_process_type', 1)->where('auxiliary_project_list.adjust_delete_time', 0)->whereNUll('auxiliary_project_list.delete_time')->order('auxiliary_project_list.work_type_sort ASC')->select();

        $paths = [];
        foreach ($list as &$item) {
            if ($item['node_ids']) {

                $app_user_order_nodes_list = Db::connect(config('database.db2'))->table('app_user_order_node')
                    ->join('app_user', 'app_user.id=app_user_order_node.user_id', 'left')
                    ->join(config('database')['database'] . '.user', 'user.user_id=app_user_order_node.user_id', 'left')
                    ->field('app_user_order_node.id,app_user_order_node.resource_ids,app_user_order_node.no_watermark_image_ids,app_user_order_node.created_at,if(app_user_order_node.distinguish=1,user.username,app_user.username) as username,app_user_order_node.distinguish')
                    ->whereIn('app_user_order_node.id', $item['node_ids'])->select();

                $pathId                    = implode(array_column($app_user_order_nodes_list, 'resource_ids'), ',');
                if ($item['type'] == 3) {
                    $pathId                    = implode(array_column($app_user_order_nodes_list, 'no_watermark_image_ids'), ',');
                }
                $path                      = Db::connect(config('database.db2'))->table('common_resource')->where('status', 1)->whereIn('id', $pathId)->field('mime_type,path,id')->select();
                foreach ($path as $k1 => $o) {

                    $listArray['path']       = 'https://images.yiniao.co/' . $o['path'];
                    $listArray['id'] =  $item['adn_id'];
                    $listArray['type']       = $app_user_order_nodes_list[0]['distinguish'];
                    $listArray['username']   = empty($app_user_order_nodes_list[0]['username']) ? "后台上传" : $app_user_order_nodes_list[0]['username'];
                    $listArray['created_at'] = date('Y-m-d H:i', $app_user_order_nodes_list[0]['created_at']);
                    $item['Img'][]            = $listArray;
                }
            } else {
                $item['node_ids'] = []; // 没有节点数据时设为空数组
                $item['Img'] = null;
            }
        }

        // 初始化结果数组
        $result = [];

        // 按 work_type_id 分组，并按 id（workingProcedureId）去重
        $grouped = [];
        foreach ($list as $item) {
            $workTypeId = $item['work_type_id'];
            $workingProcedureId = $item['id']; // 唯一标识字段

            // 处理时间格式
            $workingStart = $item['working_start'] ? date('Y-m-d', $item['working_start']) : '';
            $workingEnd = $item['working_end'] ? date('Y-m-d', $item['working_end']) : '';
             //0没有上传 1 可验收 2 已验收 3没有节点
             $isNodes=0;
                if( !empty($item['Img']) && empty($item['completion_time'])){
                     $isNodes=1;
                }elseif( !empty($item['Img']) && !empty($item['completion_time'])){
                     $isNodes=2;
                }
            // 组装 data 字段
            $dataItem = [
                'class_b' => $item['class_b'],
                'capital_id' => $item['capital_id'],
                'completeTime' => $item['completion_time'] ? date('Y-m-d', $item['completion_time']) : '',
                'orderId' => 0, // 固定值
                'workProcessId' => $item['work_process_id'],
                'username' => $item['username'] ?: null,
                'work_time' => 0, // 固定值
               'isNodes' =>  $isNodes,
            ];

            // 按 work_type_id 分组，同时记录已处理的 id
            if (!isset($grouped[$workTypeId]['ids'][$workingProcedureId])) {
                if (!isset($grouped[$workTypeId])) {
                    $grouped[$workTypeId] = [
                        'workTypeSort' => $item['work_type_sort'],
                        'typeWorkId' => $workTypeId,
                        'typeWork' => $item['work_type_title'],
                        'workTemplateId' => 1,
                        'list' => [],
                        'ids' => []
                    ];
                }
                $completionStatus=0;
                if( !empty($item['Img']) && empty($item['completion_time'])){
                    $completionStatus=1;
                }elseif( !empty($item['Img']) && !empty($item['completion_time'])){
                    $completionStatus=2;
                }
                $grouped[$workTypeId]['list'][] = [
                    'workingProcedure' => $item['work_process_title'],
                    'mainNBode' => 0,
                    'workingProcedureId' => $workingProcedureId,
                    'sort' => $item['work_process_sort'],
                    'completionStatus' => $completionStatus,
                    'working_start' => $workingStart,
                    'working_end' => $workingEnd,
                    'workTypeSaveId' => $workingProcedureId,
                    'data' => [$dataItem] // 确保 data 是数组
                ];

                $grouped[$workTypeId]['ids'][$workingProcedureId] = true; // 标记为已处理
            } else {
                // 若 id 已存在，合并 data 数据（可选，根据需求决定是否合并）
                // 示例：array_push($grouped[$workTypeId]['list'][array_search($workingProcedureId, $grouped[$workTypeId]['ids'])['data'], $dataItem);
            }
        }

        // 整理结果格式
        
        foreach ($grouped as $group) {
            $result[] = [
                'workTypeSort' => $group['workTypeSort'],
                'typeWorkId' => $group['typeWorkId'],
                'typeWork' => $group['typeWork'],
                'workTemplateId' => $group['workTemplateId'],
                'list' => $group['list']
            ];
        }
       
        return $result;
    }
    public function saveList($list,$orderdId)
    {
        $manageUpdateData = [];
        db('auxiliary_project_list')->where('work_process_type',1)->whereNUll('auxiliary_project_list.delete_time')->where('order_id',$orderdId)->where('adjust_delete_time',0)->update(['adjust_delete_time'=>time()]);
        foreach ($list as $p => $item) {
            if (!empty($item['list'])) {
                foreach ($item['list'] as $k => $value) {
                    $manageUpdateData = [
                   
                        'working_start' => strtotime($value['working_start']),
                        'working_end' => strtotime($value['working_end']),
                        'work_type_sort'=>$k,
                        'adjust_delete_time'=>0
                     
                    ];
                    db('auxiliary_project_list')->where('id',$value['workingProcedureId'])->where('order_id',$orderdId)->update($manageUpdateData);
                    
                }
            }
        }
      
    }
}
